package com.miraclengine.karma;

import java.util.ArrayList;
import java.util.List;

import org.andengine.entity.Entity;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.modifier.DelayModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.AnimatedSprite.IAnimationListener;
import org.andengine.entity.sprite.ButtonSprite;
import org.andengine.entity.sprite.ButtonSprite.OnClickListener;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.entity.text.TextOptions;
import org.andengine.entity.text.TickerText;
import org.andengine.entity.text.TickerText.TickerTextOptions;
import org.andengine.extension.texturepacker.opengl.texture.util.texturepacker.TexturePackTextureRegionLibrary;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.font.StrokeFont;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.util.HorizontalAlign;
import org.andengine.util.modifier.IModifier;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.graphics.Typeface;
import android.os.Handler;
import android.widget.Toast;

import com.miraclengine.domain.Friend;
import com.miraclengine.eventobject.EventButtonSprite;
import com.miraclengine.eventobject.EventEntity;
import com.miraclengine.texture.TextureData;
import com.miraclengine.utils.Debug;
import com.miraclengine.utils.ProgressAsyncTask;
import com.miraclengine.xml.DataTable;
import com.miraclengine.xml.XmlHttpClientHelper;


public class GameRunningScreen extends AbstractScene {
	
	private String TAG = GameRunningScreen.class.getSimpleName();
	
	private KarmaGame game;
	private TexturePackTextureRegionLibrary packer;
	private TexturePackTextureRegionLibrary packerModel;
	
	public final static int GLAYER_BG = 0;
	public final static int GLAYER_GAME = 1;
	public final static int GLAYER_UI = 2;
	public final static int GLAYER_FUI = 3;
	public final static int GLAYER_RUI = 4;
	public final static int GLAYER_COUNT = 5;
	
	public Font mFont;
	//public StrokeFont mStrokeFont;
	public Font mStrokeFont;
	public StrokeFont mAchieveFont;
	public Font mNameFont;
	
	public Font mReFont;
	
	public final static float ACHIEVE_FONT_SIZE = 20.f;
	public final static float NAME_FONT_SIZE = 18.f;
	
	public ITexture mTexture;
	
	//Sprite
	//private Sprite bg;
	private Sprite[] bookmarkIcon;
	private EventButtonSprite btnNext;
	private EventButtonSprite btnSend;
	private AnimatedSprite bookmarkEffect;
	
	private Sprite[] model = new Sprite[12];
	
	private Sprite friendchoiceBack;
	private Sprite friendchoiceFNormal;
	private Sprite friendchoiceFSelect;
	
	private EventButtonSprite fSelect;
	
	private Sprite bookmarkBack;
	
	//TextureRegion
	//private TextureRegion bgRegion;
	private TextureRegion bookmarkBackRegion;
	private TextureRegion bookmarkIconRegion;
	private TextureRegion bookmarkEffect01Region;
	private TextureRegion bookmarkEffect02Region;
	private TiledTextureRegion bookmarkEffectRegion;
	private TextureRegion btnNextNormalRegion;
	private TextureRegion btnNextSelectRegion;
	
	private TextureRegion friendchoiceBackRegion;
	private TextureRegion friendchoiceFNormalRegion;
	private TextureRegion friendchoiceFSelectRegion;
	private TextureRegion fSelectNormalRegion;
	private TextureRegion fSelectSelectRegion;
	
	//RUI
	private TextureRegion choiceBackNormalRegion;
	private TextureRegion choiceBackSelectRegion;
	
	private TextureRegion btnSendNormalRegion;
	private TextureRegion btnSendSelectRegion;
	
	
	
	private TextureRegion propic01Region;
	private TextureRegion propic02Region;
	private TextureRegion propic03Region;
	
	private List<TextureRegion> propicRegion;
	
	private TextureRegion[] modelRegion;
	
	private int sceneNumber = 0;
	private int friendNumber;
	private boolean rScene = false;
	
	private int[][] sequence = new int[][] {
			//0:그림넘버, 1:텍스트넘버, 2:책갈피사용, 3:씬넘버, 4:몰라, 5:선택 모듈(1.캐랙터선택), 6:화면이동(1:다음씬, 2:플로우), 7:이름변환씬., 8:사운드. 9:책갈피 회복. 10.경험치값, 11:pass, 12:goMenu
			{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, -1, 0},	// 0. //1-1
			{1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 8, -1, 0},	// 1. //1-2
			{2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 8, -1, 0},	// 2. //1-3
			{3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 8, -1, 0},	// 3. //1-4
			{4, 4, 1, 0, 0, 0, 0, 0, 3, 0, 8, -1, 0}, 	// 4. //1-5
			{5, 5, 1, 0, 0, 1, 1, 0, 0, 0, 8, -1, 0}, 	// 5. //1-6
			{6, 6, 0, 0, 0, 0, 0, 1, 0, 0, 8, -1, 0}, 	// 6. //1-7
			{7, 7, 0, 0, 0, 0, 3, 0, 0, 0, 8, 0, 1},	// 7. //1-8
			{8, 8, 0, 1, 0, 0, 0, 0, 0, 1, 8, -1, 0},	// 8. //2-1
			{9, 9, 1, 1, 0, 1, 2, 0, 2, 0, 0, 1, 0},	// 9. //2-2
			{10, 10, 0, 1, 0, 0, 0, 0, 0, 1, 23, 2, 0},	// 10. //2-3
			{11, 11, 0, 1, 1, 0, 0, 0, 0, 0, 23, 3, 0},	// 11. //2-4
			{-1, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0}, //12.
			{-1, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0}, //13
	};
	
	//「」
	private String[] msg = new String[] {
			"툭.. 투둑..\n\n손에서 놓친 핸드폰이 아스팔트 바닥을 둔탁하게 구르는 듯한\n소리가 머리속에 울린다.\n\n내 핸드폰인가 싶어 주위를 둘러 보려했지만..\n갑자기 눈이 부셔 눈을 질끈 감았다.\n\n그 눈부심 때문일까..?\n\n잠깐의 순간인데 오래간만의 숙면을 취한듯 찡한 두통이\n홀가분할 정도의 편안함으로 몰려들었다.",//1-1 	//0
			"두리번 거리며 혹시나 내 핸드폰을 찾아봤지만\n다행히도 떨어진것 같진 않다.\n\n\"저기야! 저기!\"\n\"어머.. 괜찮..으려나?\"\n\n몇 명의 사람들이 나를 지나쳐 웅성대는 곳으로 뛰어가고 있다.\n\n어떤일일까 궁금하긴 하지만..\n어떤 느낌이 궁금증을 누르며 발걸음을 재촉하지 않았다.\n\n게다가 사람들이 많은 곳이 그다지 유쾌하지 않았기에\n몰려가는 반대편으로 천천히 발걸음을 옮겼다.",//1-2  //1 
			"집에 도착해 현관문을 열자, 다시 찡한 두통이 몰려 왔다.\n\n이 시간에는 항상 집에서 손뜨개질을 하고 있을 엄마도 없어\n침대에 쓰러지듯 누웠다.\n",//1-3	//2
			"시간이 얼마나 지났을까,\n눈을 떠보니 얇은 커튼 사이로 어둠이 밀려오는 느낌이 들었다.\n\n이 시간에는 아빠까지 들어와 왁자지껄해야 할텐데..\n\n\n...적막속에서 다시 잠이 들었다.",//1-4(연결)	//3
			"현관문이 열리는 소리에 눈이 떠졌다.\n엄마와 아빠가 어디 다녀오셨나보다.\n\n두 분다 며칠동안 잠도 못 잔 피곤한 표정으로\n터벅터벅 들어와 쇼파에 앉아 멍한 표정을 짓고 있다.\n\n\n그런데 어떤 사람이 바로 뒤 따라 들어오더니\n집안을 두리번 거리기 시작한다.\n그러더니 나를 보고 다가온다.",//1-5	//4
			"\"여기 있었구나! 한참 찾았네\"\n\n뭐를 한참 찾았다는거지? 나..?\n\n\"그래 너.. 보통은 육신과 함께 하는데 넌 왜 여기 와 있는거야?\"\n\"응? 내 생각을 읽은거야?\"\n\"생각을 하는거나, 말을 하는거나.. 아. 아직 적응은 안되겠구나.\n당분간 내가 챙겨 줄테니 잘 부탁 해\"\n\n\"…..\"\n\"널 찾아 헤매느라 정신이 없어서 소개가 늦었네 나는..\"",//1-6	//5
			"\"나는 「사도」라고 해.. 앞으로 잘 부탁한다.\"\n\n\"난.. 지금 상황이.. 전혀 이해가 안돼.. 너 누구야..?\"\n\n\"흠.. 여기에 있어서 더욱 그럴지도 모르겠다.\n보통은 같이 따라 다니다 보면 자연스레 알게 되는데..\n\n\n넌 말야..\"",//1-7 //6
			"\n\n\n\n\n\"넌.. 죽은거야.\"",//1-8	//7
			
			"「여자」는 지난번 검사 결과를 듣기 위해 병원을 방문하였다.\n\n친구는 혹시 모르니까 같이 가자고 하는데,\n별로 탐탁치 않아 혼자 발걸음을 옮겼다.\n\n그 「친구」를 떠올리자 마자 핸드폰이 울렸다.\n\n\"얘도 양반이 아니네..\n여보세요?\"\n\"뭐야.. 혼자서 병원에 간거야? 같이 가자니까\"\n\"아냐.. 바쁠텐데.. 걱정하지마.. 별일도 아닌데..\"",//2-1	//8
			"\"기집애.. 그래도 혹시 결과가 이상하게 나왔는데,\n그런 얘기 혼자 듣는 것 만큼 슬픈건 없어.\"\n\n\"그냥 큰병 걸리게 해달라고 굿을 해라. 굿을 해\"\n\n\"농담이구.. 나 병원에 거의 다 왔는데 어딨어?\"\n\n\"병원에 왔다구..? 나 지금 엘리베이터 타려고 하는데..\"",//2-2	//9
			"\"그래? 그럼 먼저 올라가.. 따라 올라갈게.\"\n\n\"그래.. 올라가서 기다리고 있을게\"\n엘리베이터에 올라타 핸드폰을 만지작 거리는 사이 문이 닫힌다.\n\n\"잠깐만요!\"\n어떤 「남자」의 다급한 목소리가 닫힌 엘리베이터 문 사이를\n파고 들었다.\n\n「여자」는 급히 열림 버튼을 눌러 보았지만\n엘리베이터는 천천히 위로 올라가기 시작했다.",//2-3(분기1)		//10
			"\"조금만 기다려. 바로 갈게\"\n\n\"어딘데? 지금 엘리베이터 왔는데..\"\n\"지금 로비를 지나고 있어.. 어! 저기 보인다..\"\n「여자」는 엘리베이터의 버튼을 누르고 로비쪽을 바라보았다.\n\n\"잠깐만요!\"\n어떤 「남자」가 「여자」를 지나쳐 엘리베이터에 올라 탔다.\n「여자」는 창피한 느낌이 들어 친구에게 손짓을 하였다.\n\n\"괜찮으면 먼저 올라가도 될까요?\"\n약간 퉁명스런 남자의 목소리에 「여자」는 버튼을 놓았고, \n엘리베이터는 문이 닫히고 올라갔다.",//2-4(분기2)		//11
			"이번 장면은 「남자」와 「여자」처음으로 엇갈리는 씬으로\n\n뒤따라 오던 「남자」는 엘리베이터를 타지 못해 \n\n담당 의사와의 중요한 계약에 늦게 되어,\n\n이로 인해 회사에서 질책을 받게 되고\n\n정리 해고 1순위에 올라 절망을 느끼게 된다.",//12
			"이번 장면은 「남자」와 「여자」처음으로 엇갈리는 씬으로\n\n「남자」가 먼저 엘리베이터를 타고 올라가는 바람에\n\n「여자」는 검사 결과를 듣지 못한 채, 동생의 사고 소식을 듣고\n\n동생이 있는 병원 중환자실로 향한다.\n\n검사 결과를 듣고 미리 조치를 취했다면 중증으로 진행되지\n않았다.",//13
	};
	
	Text script;
	String fName;
	String fId;
	boolean isTag = false;
	
	int replaySelect;
	
	SequenceEntityModifier fadeIn;
	SequenceEntityModifier fadeOut;
	SequenceEntityModifier bookmarkInOut = new SequenceEntityModifier(new IEntityModifierListener() {
		@Override
		public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
			// TODO Auto-generated method stub
		}
		@Override
		public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
			// TODO Auto-generated method stub
		}
	},
	new AlphaModifier(0.5f, 0.1f, 1.f),
	new DelayModifier(1.f),
	new AlphaModifier(0.5f, 1.f, 0.1f)
	);

	public GameRunningScreen(KarmaGame game) {
		// TODO Auto-generated constructor stub
		this.game = game;
		this.packer = game.mSpritesheetTexturePackTextureRegionLibrary;
		this.packerModel = game.mSpritesheetTexturePackTextureRegionLibraryModel;
		
		this.mTexture = game.spritesheetTexturePack.getTexture();
		
		loadResources();
	}
	
	public void loadResources() {
		//AchieveFont
		final ITexture achieveFontTexture = new BitmapTextureAtlas(game.getTextureManager(), 256, 256, TextureOptions.BILINEAR);
		this.mAchieveFont = new StrokeFont(game.getFontManager(), achieveFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), ACHIEVE_FONT_SIZE, true, 0xffffffff, 2, 0xff804c11);
		this.mAchieveFont.load();
		
		this.mNameFont = FontFactory.create(game.getFontManager(), game.getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), NAME_FONT_SIZE, true, 0xff804c11);
		this.mNameFont.load();
		
		this.mReFont = FontFactory.create(game.getFontManager(), game.getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 22, true, 0xff02cacd);
		this.mReFont.load();
				
		//폰트 로딩.
		//final ITexture strokeFontTexture = new BitmapTextureAtlas(game.getTextureManager(), 1024, 1024, TextureOptions.BILINEAR);
		//this.mStrokeFont = new StrokeFont(game.getFontManager(), strokeFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), 27, true, Color.WHITE, 1, Color.BLACK);
		this.mStrokeFont = FontFactory.create(game.getFontManager(), game.getTextureManager(), 512, 512, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), 27, true, 0xffffffff);
		this.mStrokeFont.load();
		
		//TextureRegion
		//this.bgRegion = packer.get(TextureData.BACK_ID);
		this.bookmarkBackRegion = packer.get(TextureData.BOOKMARK_BACK_ID);
		this.bookmarkIconRegion = packer.get(TextureData.BOOKMARK_ICON_ID);
		this.bookmarkEffect01Region = packer.get(TextureData.BOOKMARK_EFFECT01_ID);
		this.bookmarkEffect02Region = packer.get(TextureData.BOOKMARK_EFFECT02_ID);
		this.bookmarkEffectRegion = new TiledTextureRegion(this.mTexture, this.bookmarkEffect01Region, this.bookmarkEffect02Region);
		this.btnNextNormalRegion = packer.get(TextureData.BTN_NEXT_NORMAL_ID);
		this.btnNextSelectRegion = packer.get(TextureData.BTN_NEXT_SELECT_ID);
		
		
		this.friendchoiceBackRegion = packer.get(TextureData.FRIENDCHOICE_BACK_ID);
		this.friendchoiceFNormalRegion = packer.get(TextureData.FRIENDCHOICE_F_NORMAL_ID);
		this.friendchoiceFSelectRegion = packer.get(TextureData.FRIENDCHOICE_F_SELECT_ID);
		this.fSelectNormalRegion = packer.get(TextureData.F_SELECT_NORMAL_ID);
		this.fSelectSelectRegion = packer.get(TextureData.F_SELECT_SELECT_ID);
		
		//RUI
		this.choiceBackNormalRegion = packer.get(TextureData.CHOICE_BACK_NORMAL_ID);
		this.choiceBackSelectRegion = packer.get(TextureData.CHOICE_BACK_SELECT_ID);
		
		this.btnSendNormalRegion = packer.get(TextureData.BTN_SEND_NORMAL_ID);
		this.btnSendSelectRegion = packer.get(TextureData.BTN_SEND_SELECT_ID);
		
		propicRegion = new ArrayList<TextureRegion>();
		
		this.propic01Region = packer.get(TextureData.PROPIC01_ID);
		propicRegion.add(this.propic01Region);
		this.propic02Region = packer.get(TextureData.PROPIC02_ID);
		propicRegion.add(this.propic02Region);
		this.propic03Region = packer.get(TextureData.PROPIC03_ID);
		propicRegion.add(this.propic03Region);
		
		modelRegion = new TextureRegion[model.length];
		for(int i=0 ; i<modelRegion.length ; i++)
			modelRegion[i] = packerModel.get(i);
	}

	@Override
	public void drawScene() {
		// TODO Auto-generated method stub
		this.setBackground(new Background(0, 0, 0));
		
		for(int i=0 ; i<GLAYER_COUNT ; i++) {
			EventEntity entity = new EventEntity(this);
			entity.setTag(i);
			this.attachChild(entity);
		}
		
		//GAME
		for(int i=0 ; i<model.length ; i++) {
			this.model[i] = new Sprite(0, 0,this.modelRegion[i], game.getVertexBufferObjectManager());
			this.model[i].setAlpha(0.1f);
		}
		
		//UI
		this.bookmarkBack = new Sprite(513, 423, this.bookmarkBackRegion, game.getVertexBufferObjectManager());
		this.getChildByIndex(GLAYER_UI).attachChild(this.bookmarkBack);
		this.bookmarkBack.setAlpha(0.1f);
		
		this.bookmarkIcon = new Sprite[5];
		for(int i=0 ; i<this.bookmarkIcon.length ; i++) {
			this.bookmarkIcon[i] = new Sprite(513+i*38, 423, this.bookmarkIconRegion, game.getVertexBufferObjectManager());
			this.bookmarkIcon[i].setAlpha(0.0f);
			this.getChildByIndex(GLAYER_UI).attachChild(this.bookmarkIcon[i]);
			
		}
		this.bookmarkEffect = new AnimatedSprite(513, 423, this.bookmarkEffectRegion, game.getVertexBufferObjectManager());
		this.getChildByIndex(GLAYER_UI).attachChild(this.bookmarkEffect);
		this.bookmarkEffect.setVisible(false);
		
		this.updateBookmarkIcon(false);
		
		//다음버튼.
		this.btnNext = new EventButtonSprite(704, 384, this.btnNextNormalRegion, this.btnNextSelectRegion, game.getVertexBufferObjectManager(), this, new OnClickListener() {
			@Override
			public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {
				if(!isNext)
					return;
				
				if(Settings.soundEnabled) {
					game.mButton1Sound.play();
				}
				
				Debug.d(TAG, "sceneNumber : " + sceneNumber);
				
				//pass true & false
				if(sequence[sceneNumber][11] != -1) {
					game.isPass[sequence[sceneNumber][11]] = true;
					Debug.d(TAG, "value : ====================== " + sequence[sceneNumber][11]);
				}
				
				if(sceneNumber < 8) {
					if(!game.isPass[0]) {
						game.mAchieve += sequence[sceneNumber][10];
					}
				} else if(sceneNumber < 10) {
					if(!game.isPass[1]) {
						game.mAchieve += sequence[sceneNumber][10];
					}
				} else if(sceneNumber < 12) {
					if(!game.isPass[2] && !game.isPass[3]) {
						game.mAchieve += sequence[sceneNumber][10];
					}
				}
				
				if(sequence[sceneNumber][5] == 1 && scriptRedirection == 0) {//캐릭터 선택 일때.
					if(rScene) {//요청을 받았을 때. true가 되어 RUI를 출력한다.
						GameRunningScreen.this.getChildByIndex(GLAYER_RUI).setVisible(true);
						GameRunningScreen.this.btnNext.setVisible(false);
						GameRunningScreen.this.unregisterTouchArea(pButtonSprite);
						rScene = false;
					} else {//요청이 아닐때는 false가 되어 FUI가 출력된다.
						if(!GameRunningScreen.this.getChildByIndex(GLAYER_FUI).isVisible()) {
							GameRunningScreen.this.getChildByIndex(GLAYER_FUI).setVisible(true);
							GameRunningScreen.this.unregisterTouchArea(pButtonSprite);
						}
					}
				} else if(sequence[sceneNumber][5] == 1 && scriptRedirection != 0) {
					updateMovieScene(false);
					sceneNumber += scriptRedirection;
					scriptRedirection = 0;
					
					if(sequence[sceneNumber][2] == 1) {
						if(game.mBookmark> 0)
							game.mBookmark --;
						updateBookmarkIcon(true);
						
						bookmarkBack.registerEntityModifier(bookmarkInOut.deepCopy());
						for(int i=0 ; i<bookmarkIcon.length ; i++) {
							bookmarkIcon[i].registerEntityModifier(bookmarkInOut.deepCopy());
						}
					}

					onScript = false;
				} else if(sequence[sceneNumber][6] == 3) {//흐름도로 이동한다.
					updateMovieScene(false);
					isTag = true;
				} else {
					if(sceneNumber >= 12) {
						updateMovieScene(false);
						isTag = true;
					} else {
						
						//마지막 씬일때는 두번씩 넘겨준다.
						if(GameRunningScreen.this.sceneNumber == 10 || GameRunningScreen.this.sceneNumber == 11) {
							updateMovieScene(false);
							GameRunningScreen.this.sceneNumber += 2;
							
						} else {
							updateMovieScene(false);
							sceneNumber ++;
						}
						
						if(sequence[sceneNumber][2] == 1) {
							if(game.mBookmark> 0)
								game.mBookmark --;
							updateBookmarkIcon(true);
							
							bookmarkBack.registerEntityModifier(bookmarkInOut.deepCopy());
							for(int i=0 ; i<bookmarkIcon.length ; i++) {
								bookmarkIcon[i].registerEntityModifier(bookmarkInOut.deepCopy());
							}
						}

						onScript = false;
					}
				}
			}
		});
		this.registerTouchArea(this.btnNext);
		this.getChildByIndex(GLAYER_UI).attachChild(this.btnNext);
		
		this.friendchoiceBack = new Sprite(39, 289, this.friendchoiceBackRegion, game.getVertexBufferObjectManager());
		this.friendchoiceBack.setTag(1001);
		this.getChildByIndex(GLAYER_FUI).attachChild(friendchoiceBack);
		
		for(int i=0 ; i<game.mFriendNum ; i++) {
			Sprite btnFriendSelect = new Sprite(64+i*104, 303, this.friendchoiceFSelectRegion, game.getVertexBufferObjectManager());
			btnFriendSelect.setTag(i+100);
			btnFriendSelect.setVisible(false);
			this.getChildByIndex(GLAYER_FUI).attachChild(btnFriendSelect);
			
			EventButtonSprite btnFriend = new EventButtonSprite(64+i*104, 303, this.friendchoiceFNormalRegion, this.friendchoiceFNormalRegion, game.getVertexBufferObjectManager(), this, new OnClickListener() {
				@Override
				public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {
					// TODO Auto-generated method stub
					Debug.d(TAG, "btnFriend select! : "  + pButtonSprite.getTag());
					for(int i=0 ; i<game.mFriendNum ; i++) {
						GameRunningScreen.this.getChildByIndex(GLAYER_FUI).getChildByTag(i + 100).setVisible(false);
					}
					GameRunningScreen.this.getChildByIndex(GLAYER_FUI).getChildByTag(pButtonSprite.getTag() + 100).setVisible(true);
					Friend friend = game.listFriend.get(pButtonSprite.getTag());
					fName = friend.getName();
					fId = friend.getId();
				}
			});
			btnFriend.setTag(i);
			
			Sprite profileImage = new Sprite(17, 37, propicRegion.get(Integer.parseInt(game.listFriend.get(i).getNo())), game.getVertexBufferObjectManager());
			btnFriend.attachChild(profileImage);
			
			String achieve = game.listFriend.get(i).getAchieve();
			achieve = achieve + "%";
			Text profileAchieve = new Text((this.friendchoiceFNormalRegion.getWidth()-achieve.length()*ACHIEVE_FONT_SIZE/2)/2, 10, this.mAchieveFont, achieve, new TextOptions(HorizontalAlign.CENTER), game.getVertexBufferObjectManager());
			btnFriend.attachChild(profileAchieve);
			
			String name = game.listFriend.get(i).getName();
			Text profileName = new Text((this.friendchoiceFNormalRegion.getWidth()-name.length()*NAME_FONT_SIZE)/2, 110, this.mNameFont, name, game.getVertexBufferObjectManager());
			btnFriend.attachChild(profileName);
			
			this.registerTouchArea(btnFriend);
			this.getChildByIndex(GLAYER_FUI).attachChild(btnFriend);
		}
		
		this.fSelect = new EventButtonSprite(638 , 322, this.fSelectNormalRegion, this.fSelectSelectRegion, game.getVertexBufferObjectManager(), this, new OnClickListener() {
			@Override
			public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {
				// TODO Auto-generated method stub
				//결정한 친구에게 링크를 보낸다. 
				Debug.d(TAG, "go Menu");
				
				if(fName == null) {
					game.runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(game, "친구선택이 되지 않았음!", Toast.LENGTH_SHORT).show();
						}
					});
					
					return;
				}
				
				//사도 캐릭터 설정한다.
				if(sequence[sceneNumber][5] == 1 && sequence[sceneNumber][6] == 1) {
					for(int i=0 ; i<game.mFriendNum ; i++) {
						GameRunningScreen.this.getChildByIndex(GLAYER_FUI).getChildByTag(i + 100).setVisible(false);
					}
					
					GameRunningScreen.this.getChildByIndex(GLAYER_FUI).setVisible(false);//FUI를 없애준다.
					GameRunningScreen.this.registerTouchArea(GameRunningScreen.this.btnNext);
					updateMovieScene(false);
					sceneNumber ++;
				} else if(sequence[sceneNumber][5] == 1 && sequence[sceneNumber][6] == 2) {//요청 친구선택.
					//요청 친구에게 요청을 보낸다.
					game.runOnUiThread(new Runnable() {
						public void run() {
							new ProgressAsyncTask(mCallBack, new Handler()).execute(game.myInfo.getId(), fId);
						}
					});
					
					for(int i=0 ; i<game.mFriendNum ; i++) {
						GameRunningScreen.this.getChildByIndex(GLAYER_FUI).getChildByTag(i + 100).setVisible(false);
					}
					
					GameRunningScreen.this.getChildByIndex(GLAYER_FUI).setVisible(false);//FUI를 없애준다.
					GameRunningScreen.this.registerTouchArea(GameRunningScreen.this.btnNext);
					
					updateMovieScene(false);
					isTag = true;
				}
				
				if(Settings.soundEnabled) {
					game.mButtonSound.play();
				}
			}
		});
		this.fSelect.setTag(1002);
		this.registerTouchArea(this.fSelect);
		this.getChildByIndex(GLAYER_FUI).attachChild(fSelect);
		
		this.getChildByIndex(GLAYER_FUI).setVisible(false);
		
		//RUI
		Sprite choice1 = new Sprite(31 , 288, this.choiceBackSelectRegion, game.getVertexBufferObjectManager());
		choice1.setTag(501);
		this.getChildByIndex(GLAYER_RUI).attachChild(choice1);
		choice1.setVisible(false);
		
		EventButtonSprite choiceBack1 = new EventButtonSprite(31 , 288, this.choiceBackNormalRegion, this.choiceBackSelectRegion, game.getVertexBufferObjectManager(), this, new OnClickListener() {
			@Override
			public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {
				// TODO Auto-generated method stub
				//A.항과 B.항을 초이스하면 상대방에게 응답이 넘어간다.
				GameRunningScreen.this.getChildByIndex(GLAYER_RUI).getChildByTag(501).setVisible(true);
				GameRunningScreen.this.getChildByIndex(GLAYER_RUI).getChildByTag(502).setVisible(false);
				
				replaySelect = 1;
				
				if(Settings.soundEnabled) {
					game.mButtonSound.play();
				}
			}
		});
		choiceBack1.setTag(1001);
		this.getChildByIndex(GLAYER_RUI).attachChild(choiceBack1);
		this.registerTouchArea(choiceBack1);
		Text ex1 = new Text(43, 22, this.mReFont, "\"그래? 그럼 먼저 올라가.. 따라 올라갈게\"", new TextOptions(HorizontalAlign.CENTER), game.getVertexBufferObjectManager());
		choiceBack1.attachChild(ex1);
		
		Sprite choice2 = new Sprite(31 , 358, this.choiceBackSelectRegion, game.getVertexBufferObjectManager());
		choice2.setTag(502);
		this.getChildByIndex(GLAYER_RUI).attachChild(choice2);
		choice2.setVisible(false);
		
		EventButtonSprite choiceBack2 = new EventButtonSprite(31 , 358, this.choiceBackNormalRegion, this.choiceBackSelectRegion, game.getVertexBufferObjectManager(), this, new OnClickListener() {

			@Override
			public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {
				// TODO Auto-generated method stub
				//A.항과 B.항을 초이스하면 상대방에게 응답이 넘어간다.
				GameRunningScreen.this.getChildByIndex(GLAYER_RUI).getChildByTag(501).setVisible(false);
				GameRunningScreen.this.getChildByIndex(GLAYER_RUI).getChildByTag(502).setVisible(true);
				
				replaySelect = 2;
				
				if(Settings.soundEnabled) {
					game.mButtonSound.play();
				}
			}
		});
		choiceBack1.setTag(1002);
		this.getChildByIndex(GLAYER_RUI).attachChild(choiceBack2);
		this.registerTouchArea(choiceBack2);
		
		Text ex2 = new Text(43, 22, this.mReFont, "\"조금만 기다려. 바로 갈게\"", new TextOptions(HorizontalAlign.CENTER), game.getVertexBufferObjectManager());
		choiceBack2.attachChild(ex2);
		
		//SendButton
		this.btnSend = new EventButtonSprite(692 , 410, this.btnSendNormalRegion, this.btnSendSelectRegion, game.getVertexBufferObjectManager(), this, new OnClickListener() {
			@Override
			public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {
				// TODO Auto-generated method stub
				
				game.runOnUiThread(new Runnable() {
					public void run() {
						new ProgressAsyncTask(mReplyCallback, new Handler()).execute(game.myInfo.getId(), game.rListFriend.get(friendNumber).getId(), Integer.toString(replaySelect));
					}
				});
				
				rScene = false;
				
				GameRunningScreen.this.getChildByIndex(GLAYER_RUI).setVisible(false);
				GameRunningScreen.this.btnNext.setVisible(true);
				GameRunningScreen.this.registerTouchArea(btnNext);
				
				updateMovieScene(false);
				isTag = true;
				
				if(Settings.soundEnabled) {
					game.mButtonSound.play();
				}
			}
		});
		this.registerTouchArea(this.btnSend);
		this.getChildByIndex(GLAYER_RUI).attachChild(this.btnSend);
		
		this.getChildByIndex(GLAYER_RUI).setVisible(false);
		
		this.setOnSceneTouchListener(new IOnSceneTouchListener() {
			@Override
			public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
				
//				if(onScript) {
//					script = new Text(30, 20, mStrokeFont, msg[sequence[sceneNumber][1]], new TextOptions(HorizontalAlign.LEFT), game.getVertexBufferObjectManager());
//					GameRunningScreen.this.getChildByIndex(GLAYER_GAME).getChildByTag(200).detachChildren();
//					GameRunningScreen.this.getChildByIndex(GLAYER_GAME).getChildByTag(200).attachChild(script);
//					onScript = false;
//				}
				onScript();
				
//				if(script != null && script.getCharactersPerSecond() != 150.f) {
//					script.setCharactersPerSecond(150.f);
//				}
				
				return false;
			}
		});
	}
	
	public void onScript() {
		if(onScript) {
			script = new Text(30, 20, mStrokeFont, msg[sequence[sceneNumber][1]], new TextOptions(HorizontalAlign.LEFT), game.getVertexBufferObjectManager());
			GameRunningScreen.this.getChildByIndex(GLAYER_GAME).getChildByTag(200).detachChildren();
			GameRunningScreen.this.getChildByIndex(GLAYER_GAME).getChildByTag(200).attachChild(script);
			onScript = false;
		}
	}
	
	boolean onScript = false;
	int scriptRedirection = 0;
	
	@Override
	public void updateScene(int sceneNumber, int friendNumber, int num) {
		// TODO Auto-generated method stub
		if(sceneNumber != 100) {
			this.sceneNumber = sceneNumber;
			
			if(friendNumber != 100) {
				this.friendNumber = friendNumber;
				if(num == 0) {
					rScene = true;
				} else {
					scriptRedirection = num;
				}
			}
		}
		
		this.updateBookmarkIcon(false);
		this.updateMovieScene(true);
	}

	public void updateBookmarkIcon(boolean bEffect) {
		Debug.d(TAG, "mBookmark : " + game.mBookmark);
		
		for(int i=0 ; i<bookmarkIcon.length ; i++)
			bookmarkIcon[i].setVisible(false);
		
		for(int i=0 ; i<game.mBookmark ; i++) 
			bookmarkIcon[i].setVisible(true);
		
		
		if(bEffect && game.mBookmark > -1) {
			bookmarkEffect.setPosition(bookmarkIcon[game.mBookmark]);
			bookmarkEffect.setVisible(true);
			bookmarkEffect.animate(new long[] {200, 200}, false, new IAnimationListener() {
				@Override
				public void onAnimationFinished(AnimatedSprite pAnimatedSprite) {
					// TODO Auto-generated method stub
					bookmarkEffect.stopAnimation();
					bookmarkEffect.setVisible(false);
				}

				@Override
				public void onAnimationStarted(AnimatedSprite pAnimatedSprite,
						int pInitialLoopCount) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onAnimationFrameChanged(AnimatedSprite pAnimatedSprite, int pOldFrameIndex, int pNewFrameIndex) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onAnimationLoopFinished(AnimatedSprite pAnimatedSprite, int pRemainingLoopCount, int pInitialLoopCount) {
					// TODO Auto-generated method stub
				}
			});
		}
	}
	
	boolean isNext = false;
	
	public void updateMovieScene(boolean in) {
		if(in) {
			fadeIn = new SequenceEntityModifier(new IEntityModifierListener() {
					@Override
					public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
						// TODO Auto-generated method stub
					}
					@Override
					public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
						// TODO Auto-generated method stub
						if(sequence[sceneNumber][7] == 1)
							msg[sequence[sceneNumber][1]] = msg[sequence[sceneNumber][1]].replace("사도", fName); 
						script = new TickerText(30, 20, mStrokeFont, msg[sequence[sceneNumber][1]], new TickerTextOptions(HorizontalAlign.LEFT, 11.f), game.getVertexBufferObjectManager());
						GameRunningScreen.this.getChildByIndex(GLAYER_GAME).getChildByTag(200).attachChild(script);
						
						isNext = true;
						onScript = true;
						
						
						if(sequence[sceneNumber][8] == 1) {
							if(Settings.soundEnabled) {
								game.mCrowdSound.play();
							}
						} else if(sequence[sceneNumber][8] == 2) {
							if(Settings.soundEnabled) {
								game.mDingSound.play();
							}
						} else if(sequence[sceneNumber][8] == 3) {
							if(Settings.soundEnabled) {
								game.mDoorSound.play();
							}
						}
					}
				},
				new AlphaModifier(1.0f, 0.f, 1.f),
				new DelayModifier(1.f),
				new AlphaModifier(1.0f, 1.f, 0.5f)
				);
			 
			this.getChildByIndex(GLAYER_GAME).detachChildren();
			if(sequence[sceneNumber][0] == -1) {
				Entity entity = new Entity();
				entity.setTag(200);
				entity.registerEntityModifier(fadeIn);
				this.getChildByIndex(GLAYER_GAME).attachChild(entity);
			} else {
				model[sequence[sceneNumber][0]].setTag(200);
				model[sequence[sceneNumber][0]].registerEntityModifier(fadeIn);
				this.getChildByIndex(GLAYER_GAME).attachChild(model[sequence[sceneNumber][0]]);
			}
		} else {
			fadeOut = new SequenceEntityModifier(new IEntityModifierListener() {
				@Override
				public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
					// TODO Auto-generated method stub
					GameRunningScreen.this.getChildByIndex(GLAYER_GAME).getChildByTag(200).detachChildren();
					isNext = false;
				}
				@Override
				public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
					// TODO Auto-generated method stub
					if(isTag) {//흐름도로 이동한다.
						if(sequence[sceneNumber][9] == 1)
							game.mBookmark = 5;
						game.switchGameToRunning(false, sequence[sceneNumber][12], 100, 0);
						GameRunningScreen.this.getChildByIndex(GLAYER_GAME).detachChildren();
						isTag = false;
					} else {
						updateMovieScene(true);
					}
				}
			},
			new AlphaModifier(1.0f, 0.5f, 0.f)
			);
			
			this.getChildByIndex(GLAYER_GAME).getChildByTag(200).registerEntityModifier(fadeOut);
		}
	}

	
	
	//통신.
	private ProgressAsyncTask.CallBack mCallBack = new ProgressAsyncTask.CallBack() {
		
		@Override
		public void onPostExecute(DataTable dt) {
			// TODO Auto-generated method stub
			//Toast.makeText(game, GlobalStatic.LAST_EXCUTE_RESULT_DESCRIPTION, Toast.LENGTH_SHORT).show();
		}
		
		@Override
		public DataTable doInBackground(String... datas) {
			// TODO Auto-generated method stub
			
			String preUrl = "http://vinchi.miraclengine.com/ServerKarma_Test/proc.php?";
			
			ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
			
			params.add(new BasicNameValuePair("mode", "request"));
			params.add(new BasicNameValuePair("id", datas[0]));
			params.add(new BasicNameValuePair("requestId", datas[1]));
			
			DataTable dt = XmlHttpClientHelper.getInstance().execute(preUrl, XmlHttpClientHelper.METHOD.GET, params);
			
			return dt;
		}
	};
	
	private ProgressAsyncTask.CallBack mReplyCallback = new ProgressAsyncTask.CallBack() {
		
		@Override
		public void onPostExecute(DataTable dt) {
			// TODO Auto-generated method stub
			//Toast.makeText(game, GlobalStatic.LAST_EXCUTE_RESULT_DESCRIPTION, Toast.LENGTH_SHORT).show();
		}
		
		@Override
		public DataTable doInBackground(String... datas) {
			// TODO Auto-generated method stub
			
			String preUrl = "http://vinchi.miraclengine.com/ServerKarma_Test/proc.php?";
			
			ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
			
			params.add(new BasicNameValuePair("mode", "reply"));
			params.add(new BasicNameValuePair("id", datas[0]));
			params.add(new BasicNameValuePair("replyId", datas[1]));
			params.add(new BasicNameValuePair("answer", datas[2]));
			
			DataTable dt = XmlHttpClientHelper.getInstance().execute(preUrl, XmlHttpClientHelper.METHOD.GET, params);
			
			return dt;
		}
	};
}
